package hhm.wcnmd.core.exec;

import java.io.IOException;
import java.util.Map;

import hhm.wcnmd.core.Constants;
import hhm.wcnmd.core.TelNetsInstance;
import hhm.wcnmd.core.exection.DuplicateSocketExection;
import hhm.wcnmd.core.model.CmdResponse;
import hhm.wcnmd.core.model.ConnectResponse;

public class WcnmdProxy {

	private String connectToken;

	public WcnmdProxy(String connectToken) {

		this.connectToken = connectToken;

	}

	public ConnectResponse connect(Map<String, String> map) {

		String host = map.get("host");
		int port = Integer.parseInt(map.get("port"));
		String username = map.get("username");
		String password = map.get("password");

		TelNetsInstance telNetInstance = TelNetsInstance.getInstance(connectToken);

		ConnectResponse response = new ConnectResponse();
		try {
			telNetInstance.connect(host, port, username, password, response);
		} catch (DuplicateSocketExection e) {
			response.setSuccess(false).setMsg(e.getMessage());
		}
		response.setConnectToken(connectToken);
		return response;
	}

	public CmdResponse disconnect() {
		TelNetsInstance telNetInstance = TelNetsInstance.getInstance(connectToken);

		CmdResponse response = new CmdResponse();

		telNetInstance.disconnect(connectToken);

		return response.setSuccess(true).setMsg("断开成功");
	}

	public CmdResponse exec(String cmdStr) {
		TelNetsInstance telNetInstance = TelNetsInstance.getInstance(connectToken);

		CmdResponse response = new CmdResponse();

		if (cmdStr.equals(" ")) {
			cmdStr = Constants.KEY_SPACE;
		}

		try {
			telNetInstance.setExecCmd(cmdStr).sendCommand().handleResult(response);
		} catch (IOException e) {
			response.setSuccess(false).setMsg("连接出错");
			e.printStackTrace();
		}
		return response;
	}

}
